/**
 * Created by ruiyuan on 15-9-23.
 */
'use strict';

var params = {};
var tempArray = window.location.search.split('?');
if (tempArray.length == 2) {
    var parts = tempArray[1].split('&');
    for (var i = 0; i < parts.length; i++) {
        var nv = parts[i].split('=');
        if (!nv[0]) continue;
        params[nv[0]] = nv[1] || true;
    }
}


var detailApp = angular.module('detailApp', ['ngRoute', 'ngResource', 'marketFilters']);
//var host = 'localhost:3000';
/*var host = 't.app.66xiaoqu.com';*/
/*  宝宝树66小区二次改造    mod   dayu  20170724   start   */
// var host = 'app.66xiaoqu.com'; // 临时用
// var host = 'app.h2oprint.com';
var host = 'app-66xiaoqu.babytree.com'; // 最终用
/*  宝宝树66小区二次改造    mod   dayu  20170724   end   */
var h5Host = host.replace('app', 'h5');
var resHost = host.replace('app', 'img');
if (host.indexOf('t') >= 0) {
    resHost = host.replace('app', 'res');
}
var detailShareUrl = 'http://' + h5Host + '/app/share/share_detail.html?token=' + params.token + '&goodsId=' + params.goodsId;

var replyTo;
var replyId;

function replyTo1(nickName, uidTmp, replyIdTmp) {
    $('.text').focus();
    $('#replyText').attr('placeholder', '回复' + nickName);
    replyTo = uidTmp;
    replyId = replyIdTmp;
}

function toPeronalPage1(uid) {
    var type = params.type;
    if (type == 'ios') {
        document.location.href = "66xiaoqu:toPeronalPage##userId=" + uid;
    } else {
        webviewhandle.goToPeronalPage(uid);//webviewhandle为webview注册对象
    }
}

function showImage(images, index) {
    var type = params.type;
    if (type == 'android') {
        webviewhandle.showImage(images, index);//webviewhandle为webview注册对象
    } else if (type == 'ios') {
        var vCode = params.vcode;
        if (vCode != null && parseInt(vCode) > 200033) {
            document.location.href = "66xiaoqu:showImage##images=" + images + "&nbsp;index=" + index;
        }
    }
}

detailApp.controller('GoodsDetailCtrl', ['$scope', '$http', 'GoodsDetail', 'ReplyList', 'Reply', 'SendMsg',
    function ($scope, $http, GoodsDetail, ReplyList, Reply, SendMsg) {
        $('.swiper-wrapper').attr('style', 'height: ' + $(document.body).width() + 'px;');
        $('.swiper-container').attr('style', 'height: ' + $(document.body).width() + 'px;');

        var type = params.type;

        $scope.itemTypeWord = {1:'闲置',2:"服务"};

        GoodsDetail.get(function (result) {
                params.token = result.data.userId;
                $scope.nickName = result.data.createdBy.nickName;
                $scope.communityName = result.data.community.communityName;
                $scope.detail = result.data;
                $scope.headImg = result.data.createdBy.images[0].imageURL;

                var dealStatus = $scope.detail.dealStatus;

                var sharePic = "";
                if (result.data.images != null && result.data.images.length > 0) {
                    sharePic = result.data.images[0].imageURL;
                }

                var shareTitle = $scope.detail.title;
                var shareDesc = $scope.detail.desc;

                if ($scope.detail.type == 2) {
                    $('.preprice').html("");
                    $scope.detail.presentPrice = "免费";
                }
                //if ($scope.detail.dealStatus == 0) {
                //    $('.saled-icon-w').hide();
                //}
                if (params.token == result.data.createdBy.objId) {
                    $('.contact').hide();
                    $scope.nickName = "我";
                }

                if (result.data.distance != null)
                    $('.fr').html(result.data.distance);

                //var isFollowUp = result.data.isFollowUp;
                //if (type == 'ios') {
                //    document.location.href = "66xiaoqu:market:followup##isFollowUp=" + isFollowUp;
                //} else {
                //    webviewhandle.checkGoodsFollowup(isFollowUp+"");//webviewhandle为webview注册对象
                //}

                if (result.data.replyCount > 0) {
                    $('#reply').html('<img src="images/debate.png">' + result.data.replyCount);
                } else {
                    $('#reply').html('<img src="images/debate.png">评论');
                    $('.comment').html('<br /><center style="font-size: 14px;color: #A8A8A8;">心动就赶紧下手吧~</center>');
                    $('.loadingMore,.comment').css('background', '#efebec');
                }
                if (result.data.collectionNum > 0) {
                    $scope.collectionNum = result.data.collectionNum;
                } else {
                    $scope.collectionNum = '收藏';
                }

                if ($scope.detail.isFollowUp) {
                    $('#collectionImg').attr("src", "images/stored.png").attr("style", "color:#fc724d");
                    $('#collectionNum').attr("style", "color:#fc724d");
                    $('.ng-binding').addClass('ng-binding-srored');
                }

                $('.avatar').attr('src', result.data.createdBy.images[0].imageURL);

                var str = "";
                var imageList = new Array();
                for (var i = 0; i < result.data.images.length; i++) {
                    imageList.push(result.data.images[i].bigImage);
                }
                for (var i = 0; i < result.data.images.length; i++) {
                    str += '<div class="swiper-slide" style="height: ' + screen.width + 'px;"><img onclick="showImage(\'' + imageList + '\',\'' + i + '\')" src="' + result.data.images[i].imageURL + '"> </div>';
                }
                $('.swiper-wrapper').attr('style', 'style="height: ' + screen.width + 'px;"').html(str);

                var mySwiper = new Swiper('.swiper-container', {
                    pagination: '.pagination',
                    paginationClickable: true,
                    onTouchMove: function () {
                        //$('.second-detail .swiper-container .clearfix').hide();
                    }
                });

                var isMore = true;//判断是否有更多数据
                var isfinish = true;//isfinish判断每次数据是否加载完成，完成了才可进行下一次加载

                $scope.ts = 0;
                $scope.getNewData = function (flag) {
                    isfinish = false;
                    ReplyList.get({
                            ts: $scope.ts
                        }, function (result) {
                            $('.loading').hide();
                            $scope.ts = result.data.ts;
                            //if (flag) {
                            //    $scope.replyList = result.data.list;
                            //} else {
                            //    $scope.replyList = $scope.replyList.concat(result.data.list);
                            //}

                            var list = result.data.list;

                            var str = "";
                            for (var i = 0; i < list.length; i++) {
                                var item = list[i];
                                str += '<li class="comment-li clearfix">';
                                str += '<img src="' + item.headImg + '" class="avatar fl" onclick="toPeronalPage1(\'' + item.repliedBy.objId + '\')">';
                                str += '<div class="comment-detail fl" style="word-break: break-all;" id="' + item.objId + ';' + item.repliedBy.objId + '" onclick="replyTo1(\'' + item.repliedBy.nickName + '\',\'' + item.repliedBy.objId + '\',\'' + item.objId + '\')">';
                                if (list[i].replyTo != null && list[i].replyTo != '') {
                                    if (params.token == item.repliedBy.objId) {
                                        str += '<span class="me">我&nbsp;回复</span>' + item.replyTo.nickName;
                                    } else {
                                        str += '<span class="me">' + item.repliedBy.nickName + '&nbsp;回复</span>' + item.replyTo.nickName;
                                    }
                                    str += '<p class="sub-comment">' + item.replyDesc + '</p> ';
                                    str += '<div   class="parent-comment-w" id="' + item.objId + ';' + item.repliedBy.objId + '">';
                                    str += '<span class="irrow"></span>';
                                    str += '<p class="parent-comment">' + item.replyTo.nickName + "说：" + item.quoteId.replyDesc + '</p></div> ';
                                } else {
                                    str += '<span class="name">' + item.repliedBy.nickName + '</span>';
                                    str += ' <p>' + item.replyDesc + '</p>';
                                    str += ''
                                }
                                str += '<span class="info">';
                                str += formatTime(item.dateReplied) + '发布在&nbsp;' + item.community.communityName + '</span> </div> </li>';
                            }

                            $('.comment').html($('.comment').html() + str);

                            isfinish = true;
                            if (result.data.list.length == 0) {
                                isMore = false;
                                $(".loadingMore").html('');
                            }
                        }
                    )
                    ;
                };

                $scope.getNewData(true);


                $('.wrapper').scroll(function () {
                    if (isMore && isfinish) {
                        var contentHeight = $(".wrapper")[0].scrollHeight;
                        var h = $(".wrapper").height();
                        if ((contentHeight - h - $(this).scrollTop()) <= 105) {
                            $(".loadingMore").html('<img src="images/refresh.gif" />正在加载');
                            //此处为加载下一条的方法
                            $scope.getNewData(false);
                        }
                    } else {
                        $(".loadingMore").html('');
                    }
                }).scroll();

                $scope.followup = function () {
                    $('.loading-con').html('<img src="images/loading.gif">');
                    $('.loading').show();
                    if (!$scope.detail.isFollowUp) {
                        $http.post('http://' + host + '/rest/v1.0/users/followup/goods/' + params.goodsId + '/' + params.token + "/" + params.deviceId, {}, {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                        }).success(function (data) {
                            $scope.detail.isFollowUp = true;
                            if (!isNaN($scope.collectionNum)) {
                                $scope.collectionNum = parseInt($scope.collectionNum) + 1;
                            } else {
                                $scope.collectionNum = 1;
                            }
                            $('#collectionNum').attr("style", "color:#fc724d");
                            $('#collectionImg').attr("src", "images/stored.png");
                            $('.ng-binding').addClass('ng-binding-srored');
                            $('.loading-con').html('收藏成功');
                            setTimeout(function () {
                                $('.loading').hide();
                            }, 1000);
                        }).error(function () {

                        });
                    } else {
                        $http.post('http://' + host + '/rest/v1.0/users/cancelFollowup/goods/' + params.goodsId + '/' + params.token + "/" + params.deviceId, {}, {
                            headers: {'Content-Type': 'application/json;charset=utf-8'}
                        }).success(function (data) {
                            $scope.detail.isFollowUp = false;
                            $scope.collectionNum = parseInt($scope.collectionNum) - 1;

                            $('#collectionNum').removeAttr("style");
                            $('#collectionImg').attr("src", "images/store.png");
                            $('.ng-binding').removeClass('ng-binding-srored');
                            $('.loading-con').html('取消收藏成功');
                            setTimeout(function () {
                                $('.loading').hide();
                            }, 1000);
                        }).error(function () {

                        });
                    }
                }

                $scope.delReply = function (replyId) {
                    $('.loading-con').html('<img src="images/loading.gif">');
                    $('.loading').show();
                    $http.post('http://' + host + '/rest/v1.0/market/delGoodsReply/' + params.goodsId + '/' + replyId + '/' + params.token + "/" + params.deviceId, {}, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (data) {

                        $('.loading-con').html('删除成功');
                        setTimeout(function () {
                            $('.loading').hide();
                        }, 1000);
                    }).error(function () {

                    });
                }

                $scope.reply = function () {
                    //$('.loading').show();
                    if (!$scope.replyDesc) {
                        $('.loading-con').html('请填写评论');
                        setTimeout(function () {
                            $('.loading').hide();
                        }, 1000);
                        return;
                    }
                    Reply.get({
                            replyDesc: $scope.replyDesc,
                            goodsId: params.goodsId,
                            replyTo: replyTo,
                            replyId: replyId
                        }, function (result) {
                            $('.loading').hide();

                            if (type == 'ios') {
                                document.location.href = "66xiaoqu:webview:toast##content=" + result.result.message + "&nbsp;status=1";
                            } else {
                                webviewhandle.showToast(result.result.message, 1);
                            }


                            var str = "";

                            var item = result.data;

                            str += '<li class="comment-li clearfix"  style="background:#fff">';
                            str += '<img src="' + item.headImg + '" class="avatar fl" onclick="toPeronalPage1(\'' + item.repliedBy.objId + '\')">';
                            str += '<div class="comment-detail fl" style="word-break: break-all;" id="' + item.objId + ';' + item.repliedBy.objId + '" onclick="replyTo1(\'' + item.repliedBy.nickName + '\',\'' + item.repliedBy.objId + '\',\'' + item.objId + '\')">';
                            if (item.replyTo != null && item.replyTo != '') {
                                str += '<span class="me">我&nbsp;回复</span>' + item.replyTo.nickName;
                                str += '<p class="sub-comment"  style="word-break: break-all;">' + item.replyDesc + '</p> ';
                                str += '<div class="parent-comment-w"  id="' + item.objId + ';' + item.repliedBy.objId + '">';
                                str += '<span class="irrow"></span>';
                                str += '<p class="parent-comment">' + item.replyTo.nickName + "说：" + item.quoteId.replyDesc + '</p></div> ';
                            } else {
                                str += '<span class="name">' + item.repliedBy.nickName + '</span>';
                                str += ' <p>' + item.replyDesc + '</p>';
                                str += ''
                            }
                            str += '<span class="info">';
                            str += formatTime(item.dateReplied) + '发布在&nbsp;' + item.community.communityName + '</span> </div> </li>';

                            $('.comment').html(str + $('.comment').html());


                            //$scope.replyList.unshift(result.data);
                            $scope.replyDesc = "";
                        }
                    )
                    ;
                };

                //长按删除
                var touchTime = 0;
                var touchT;
                $(document).on('touchstart', function (ev) {
                    touchTime = 0;
                    var _target = ev.target.parentNode;
                    if (_target.className == 'comment-detail fl' || _target.className == 'parent-comment-w') {
                        if (params.token != _target.id.split(';')[1]) {
                            return;
                        }
                        $('.loading-con').html('点击删除');
                        touchT = setInterval(function () {
                            touchTime++;
                            if (touchTime > 10) {
                                clearInterval(touchT);
                                $('.delete-comment-pop').show();
                                $('.loading-con').on('touchstart', function () {
                                    var replyId = _target.id.split(';')[0];
                                    if (_target.className == 'comment-detail fl') {
                                        $(_target).parents('li').remove();
                                    }
                                    if (_target.className == 'parent-comment-w') {
                                        $(_target).remove();
                                    }
                                    $('.delete-comment-pop').hide();
                                    $scope.delReply(replyId);
                                    return false;
                                });
                            }

                        }, 50);
                    }
                });
                $(document).on('touchmove', function (ev) {
                    touchTime = 0;
                    clearInterval(touchT);
                });
                $(document).on('touchend', function (ev) {
                    touchTime = 0;
                    clearInterval(touchT);
                });
                $('.delete-comment-pop').on('touchstart', function () {
                    $(this).hide();
                });

                var isClear = true;
                $scope.clearReplyTo = function () {
                    if (!isClear) {
                        return;
                    }
                    $('#replyText').attr('placeholder', '说点什么吧...');
                    replyTo = null;
                    replyId = null;
                }

                $scope.moveClearReplyTo = function () {
                    isClear = false
                }
                $scope.addClearReplyTo = function () {
                    isClear = true;
                }

                $scope.toPeronalPage = function (uid) {
                    if (type == 'ios') {
                        document.location.href = "66xiaoqu:toPeronalPage##userId=" + uid;
                    } else {
                        webviewhandle.goToPeronalPage(uid);//webviewhandle为webview注册对象
                    }
                };

                $scope.contact = function () {
                    SendMsg.save({}, {
                        huanxinUserName: result.data.createdBy.huanxinUserName,
                        goodsId: params.goodsId,
                        message: '你好，我想购买你的' + result.data.title + '。'
                    });
                    if (type == 'ios') {
                        document.location.href = "66xiaoqu:market:contact##userId=" + result.data.createdBy.objId + "&nbsp;nickName=" + result.data.createdBy.nickName + "&nbsp;imageURL=" + result.data.createdBy.images[0].imageURL + "&nbsp;huanxinUserName=" + result.data.createdBy.huanxinUserName;
                    } else {
                        webviewhandle.contactCreatedUser(JSON.stringify(result.data.createdBy));//webviewhandle为webview注册对象
                    }
                };

                var title = $scope.communityName + "的闲置物品【" + result.data.title + "】";

                $scope.share = function () {
                    if (type == 'ios') {
                        document.location.href = "66xiaoqu:market:share##title=" + title + "&nbsp;desc=" + result.data.desc + "&nbsp;image=" + result.data.images[0].imageURL + "&nbsp;url=" + detailShareUrl;
                    } else {
                        webviewhandle.shareGoodsDetail(title, result.data.desc, result.data.images[0].imageURL, detailShareUrl);//webviewhandle为webview注册对象
                    }
                };
                $('.loading-pop').hide();
                if (type == 'ios') {
                    document.location.href = "66xiaoqu:market:detail##dealStatus=" + dealStatus + "&nbsp;desc=" + shareDesc + "&nbsp;title=" + title + "&nbsp;image=" + sharePic + "&nbsp;url=" + detailShareUrl + "&nbsp;createdBy=" + result.data.createdBy.objId;
                } else {
                    webviewhandle.goToMarketDetail(dealStatus, detailShareUrl, sharePic, title, shareDesc, result.data.createdBy.objId);//webviewhandle为webview注册对象
                }
            }
        )

    }
]).
    controller('ActivityDetailCtrl', ['$scope', '$http', 'ActivityDetail', '$location', function ($scope, $http, ActivityDetail, $location) {

        if (params.activityId == null) {
            params.activityId = params.id;
        }
        if (params.token != null && params.token != '') {
            $http.get('http://' + host + '/rest/v1.0/activity/getCommunityActivity/' + params.activityId + '/' + params.token + '/' + params.deviceId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                setShareContent(data.data.shareKey);
                $scope.activity = data.data;
                $scope.phone = data.data.partakeMobile;
                //$scope.activity.explain = $scope.activity.explain.replace('\n','<br />');
                if (data.data.isPartake == true) {
                    $('.join-a').addClass('joined-a').html('已报名');
                    checkOk = true;
                    //checkOk = true;
                }

                if ($scope.activity.charge == null || $scope.activity.charge == 0) {
                    $('.fr').html('<em class="num" id="charge">免费</em>');
                } else {
                    $('#charge').html($scope.activity.charge + '<sub>元/位</sub>');
                }

                var str = "";
                for (var i = 0; i < data.data.images.length; i++) {
                    str += '<div class="swiper-slide"><img src="' + data.data.images[i].imageURL + '"> </div>';
                }
                $('.swiper-wrapper').html(str);
                var mySwiper = new Swiper('.swiper-container', {
                    pagination: '.pagination',
                    paginationClickable: true,
                    onTouchMove: function () {
                        //$('.second-detail .swiper-container .clearfix').hide();
                    }
                });
            });

        } else {
            $('.join-a').html('点击下载');
            $http.get('http://' + host + '/rest/v1.0/activity/getCommunityActivityForOutside/' + params.activityId , {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                $scope.activity = data.data;

                if ($scope.activity.charge == null || $scope.activity.charge == 0) {
                    $('.fr').html('<em class="num" id="charge">免费</em>');
                } else {
                    $('#charge').html($scope.activity.charge + '<sub>元/位</sub>');
                }

                var str = "";
                for (var i = 0; i < data.data.images.length; i++) {
                    str += '<div class="swiper-slide"><img src="' + data.data.images[i].imageURL + '"> </div>';
                }
                $('.swiper-wrapper').html(str);
                var mySwiper = new Swiper('.swiper-container', {
                    pagination: '.pagination',
                    paginationClickable: true,
                    onTouchMove: function () {
                        //$('.second-detail .swiper-container .clearfix').hide();
                    }
                });
            });
        }

        $scope.partake = function () {
            if (checkOk || !($('#mobilePhone').val() != '' && $('#address').val() != '')) return;
            var opt = {
                type: $scope.activity.type,
                phone: $scope.phone,
                desc: $scope.desc
            }
            $http.post('http://' + host + '/rest/v1.0/activity/partakeCommunityActivity/' + params.activityId + '/' + params.token + '/' + params.deviceId, opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.activity.partakeCount = parseInt($scope.activity.partakeCount) + 1;
                $('.join-a').addClass('joined-a').html('已报名');
                checkOk = true;
            });
        }
    }]);
;


detailApp.factory('GoodsDetail', ['$resource',
    function ($resource) {
        //请求接口
        return $resource('http://' + host + '/rest/v1.0/market/getGoodsDetail/' + params.goodsId + '/' + screen.width + '/' + params.token + '/' + params.deviceId + '?clickSource=' + params.clickSource,
            {}
        );
    }]);

detailApp.factory('ReplyList', ['$resource',
    function ($resource) {
        //请求接口
        return $resource('http://' + host + '/rest/v1.0/market/getRepliesByGoodsId/' + params.goodsId + '/' + params.token + '/' + params.deviceId,
            {}
        );
    }])

detailApp.factory('Reply', ['$resource',
    function ($resource) {
        //请求接口
        return $resource('http://' + host + '/rest/v1.0/market/addReply/' + params.token + '/' + params.deviceId,
            {}
        );
    }]);

detailApp.factory('ActivityDetail', ['$resource',
    function ($resource) {
        //请求接口
        return $resource('http://' + host + '/rest/v1.0/activity/getCommunityActivity/' + params.activityId + '/' + params.token + '/' + params.deviceId,
            {}
        );
    }]);

detailApp.factory('SendMsg', ['$resource',
    function ($resource) {
        return $resource('http://' + host + '/rest/v1.0/market/goodsDetail/sendMessage/' + params.token + '/' + params.deviceId,
            {}
        );
    }
]);

function formatTime(input) {

    var d = new Date(input), now = new Date(),
        dStamp = d.getTime(), nowStamp = now.getTime();
    if (now.getFullYear() - d.getFullYear() > 0) {
        return d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
    } else if ((nowStamp - dStamp) / 1000 < 60) {
        return "刚刚";
    } else if ((nowStamp - dStamp) / 60000 < 60) {
        return Math.floor((nowStamp - dStamp) / 60000) + "分钟前";
    } else if ((nowStamp - dStamp) / 3600000 < 24) {
        return Math.floor((nowStamp - dStamp) / 3600000) + "小时前";
    } else if ((nowStamp - dStamp) / 86400000 >= 1 && (nowStamp - dStamp) / 86400000 <= 3) {
        return Math.floor((nowStamp - dStamp) / 86400000) + "天前";
    } else if ((nowStamp - dStamp) / 86400000 > 3) {
        return (d.getMonth() + 1) + "月" + d.getDate() + "日";
    }
};

function UrlEncode(str) {
    var ret = "";
    var strSpecial = "!#$%&'()*+,/:;<=>?[]^`{|}~%";
    for (var i = 0; i < str.length; i++) {
        var chr = str.charAt(i);
        var c = str2asc(chr);
        if (parseInt("0x" + c) > 0x7f) {
            ret += "%" + c.slice(0, 2) + "%" + c.slice(-2);
        } else {
            if (chr == " ")
                ret += "+";
            else if (strSpecial.indexOf(chr) != -1)
                ret += "%" + c.toString(16);
            else
                ret += chr;
        }
    }
    return ret;
}

function setShareContent(key) {

    if (params.vcode != null && parseInt(params.vcode) >= 201000) {
        var xhr = new XMLHttpRequest();

        xhr.open("POST", 'http://' + host + '/rest/v1.0/mobile/shares/getShareContentByKey/' + key, true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function () {
            var XMLHttpReq = xhr;
            if (XMLHttpReq.readyState == 4) {
                if (XMLHttpReq.status == 200) {
                    var text = XMLHttpReq.responseText;
                    var data = JSON.parse(text);
                    var title = data.data.title;
                    var desc = data.data.desc;
                    var image = data.data.shareImg;
                    var url = encodeURIComponent(data.data.url);
                    if (params.type == 'ios') {
                        document.location.href = "66xiaoqu:setShareContent##title=" + title + "&nbsp;desc=" + desc + "&nbsp;image=" + image + "&nbsp;url=" + url;
                    } else {
                        webviewhandle.setShareContent(title, desc, image, url);//webviewhandle为webview注册对象
                    }
                }
            }
        };
        xhr.send();
    }
}
